﻿namespace DomainServices.Tools
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Globalization;
    using System.Reflection;

    internal class ValidationCustomAttributeBuilder : StandardCustomAttributeBuilder
    {
        public override AttributeDeclaration GetAttributeDeclaration(Attribute attribute)
        {
            ValidationAttribute validationAttribute = (ValidationAttribute) attribute;
            AttributeDeclaration attributeDeclaration = base.GetAttributeDeclaration(attribute);
            RegisterSharedResources(validationAttribute, attributeDeclaration);
            return attributeDeclaration;
        }

        protected static void RegisterSharedResources(ValidationAttribute validationAttribute, AttributeDeclaration attributeDeclaration)
        {
            string errorMessageResourceName = validationAttribute.ErrorMessageResourceName;
            Type errorMessageResourceType = validationAttribute.ErrorMessageResourceType;
            bool flag = string.IsNullOrEmpty(errorMessageResourceName);
            Type type = validationAttribute.GetType();
            if (((errorMessageResourceType != null) && flag) || ((errorMessageResourceType == null) && !flag))
            {
                string str2 = (errorMessageResourceType != null) ? errorMessageResourceType.Name : Resource.Unspecified_Resource_Element;
                string str3 = flag ? Resource.Unspecified_Resource_Element : errorMessageResourceName;
                attributeDeclaration.Errors.Add(string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_ValidationAttribute_Requires_ResourceType_And_Name, new object[] { type, str2, str3 }));
            }
            else if (errorMessageResourceType != null)
            {
                PropertyInfo property = errorMessageResourceType.GetProperty(errorMessageResourceName);
                if (property == null)
                {
                    attributeDeclaration.Errors.Add(string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_ValidationAttribute_ResourcePropertyNotFound, new object[] { type, errorMessageResourceName, errorMessageResourceType }));
                }
                else
                {
                    attributeDeclaration.RequiredTypes.Add(errorMessageResourceType);
                    attributeDeclaration.RequiredProperties.Add(property);
                }
            }
        }
    }
}

